﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;

namespace PesticideManage.API.Filters;

public class SampleExceptionFilter : IActionFilter, IOrderedFilter
{
    private readonly IHostEnvironment _environment;

    public SampleExceptionFilter(IHostEnvironment environment)
    {
        _environment = environment;
    }
    public int Order => int.MaxValue - 10;

    public void OnActionExecuting(ActionExecutingContext context)
    {

    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Exception is not null)
        {
            ProblemDetails problem = new ProblemDetails()
            {
                Status = 500,
                Title = context.Exception.Message,
            };
            if (_environment.IsDevelopment())
            {
                problem.Detail = context.Exception.ToString();
                problem.Extensions.Add("exceptionType", context.Exception.GetType().Name);
            }
            //StringBuilder problem = new();
            //problem.AppendLine(context.Exception.Message);

            //if (_environment.IsDevelopment())
            //{
            //    problem.AppendLine(context.Exception.GetType().FullName);
            //    problem.AppendLine(context.Exception.StackTrace);
            //}
            context.Result = new ObjectResult(problem);

            context.ExceptionHandled = true;
        }
    }
}
public class ExceptionFilter : IExceptionFilter
{
    private readonly IHostEnvironment _hostEnvironment;

    public ExceptionFilter(IHostEnvironment hostEnvironment) =>
        _hostEnvironment = hostEnvironment;

    public void OnException(ExceptionContext context)
    {
        //if (!_hostEnvironment.IsDevelopment())
        //{
        //    // Don't display exception details unless running in Development.
        //    return;
        //}
        ProblemDetails problem = new ProblemDetails()
        {
            Status = 500,
            Title = context.Exception.Message,
        };
        if (_hostEnvironment.IsDevelopment())
        {
            problem.Detail = context.Exception.ToString();
            problem.Extensions.Add("exceptionType", context.Exception.GetType().Name);
        }
        //context.Result = new ContentResult
        //{
        //    Content = context.Exception.ToString()
        //};
        context.Result = new ObjectResult(problem);

       // context.ExceptionHandled = true;
    }
}
